<template>
  <div class="news-container">
    <div class="news-template">
      <div class="news-template-main">
        <div class="news-template-box">
         <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="模板名称" label-width="134px" prop="name">
              <div v-show="!showName">{{this.ruleForm.name}} <i class="el-icon-edit" @click="editName"></i></div>
              <el-input v-show="showName" v-model="ruleForm.name" placeholder="请输入合同模板名称" @blur="editName"></el-input>
            </el-form-item>
            <el-form-item label="模板编号" label-width="134px" prop="number">
                {{this.ruleForm.number}}
              <el-input v-show="showNumber" v-model="ruleForm.number" placeholder="自动生成（规则待定）"></el-input>
            </el-form-item>
            <el-form-item label="合同类型" label-width="134px" prop="type">
              <el-radio-group v-model="ruleForm.type">
                <el-radio label="2">适用个人类客户</el-radio>
                <el-radio label="3">适用公司类客户</el-radio>
                <el-radio label="1">通用类</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="适用范围" label-width="134px" prop="type">
              <el-radio-group v-model="ruleForm.range">
                <el-radio v-for="item in scopelist"  :label="item.id" :key="item.id">{{item.value}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item label="模板图标" class="icon-list" label-width="134px" prop="iconList">
              <div class="icon-list-item" v-for="(item, index) in ruleForm.draftList" :key="index">
                  <i class="el-icon-tickets"></i>
              </div>
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :file-list="ruleForm.iconList"
                v-model="ruleForm.iconList"
                :on-change="handleChangeIcon"
                :on-remove="handleRemoveIcon"
                :auto-upload="false"
                >
                <el-button size="small"><i class="el-icon-upload2"></i>重新上传图片</el-button>
              </el-upload>
            </el-form-item> -->
            <el-form-item label="模板底稿" class="icon-list" label-width="134px" prop="draftList">
              <div class="file-list-item" v-for="(item, index) in ruleForm.draftList" :key="index">
                  <i>{{item.name}}</i>
              </div>
              <el-upload
                class="upload-demo"
                id="uploaddom"
                action="https://jsonplaceholder.typicode.com/posts/"
                :file-list="ruleForm.draftList"
                v-model="ruleForm.draftList"
                :on-change="handleChangeDraft"
                :on-remove="handleRemoveDraft"
                :auto-upload="false"
                ref='upload'
                >
                <el-button size="small"><i class="el-icon-upload2"></i>重新上传文件</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item class="form-indate" label="模板有效期" label-width="134px" prop="type">
              <el-radio-group v-model="ruleForm.datetype" @change="radioChecked">
                <el-row type="flex" align="middle">
                  <el-radio label="固定日期"></el-radio>
                    <el-col class="form-indate-item">
                      <el-form-item prop="date1">
                        <el-date-picker type="date" placeholder="选择日期" @change="handleTimeChange" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col class="line" :span="2">至</el-col>
                    <el-col class="form-indate-item">
                      <el-form-item prop="date2">
                        <el-date-picker placeholder="选择时间" @change="handleTimeChange" v-model="ruleForm.date2" style="width: 100%;"></el-date-picker>
                      </el-form-item>
                    </el-col>
                </el-row>

              </el-radio-group>
            </el-form-item>
            <el-form-item label="合同描述" label-width="134px" prop="message">
              <el-input v-model="ruleForm.message"></el-input>
            </el-form-item>
            <el-form-item class="lv-input" label="级别" label-width="134px" prop="message">
              <el-select v-model="ruleForm.lv">
                          <el-option label="1" value="1"></el-option>
                          <el-option label="2" value="2"></el-option>
                          <el-option label="3" value="3"></el-option>
                          <el-option label="4" value="4"></el-option>
                          <el-option label="5" value="5"></el-option>
                          <el-option label="6" value="6"></el-option>
                          <el-option label="7" value="7"></el-option>
                          <el-option label="8" value="8"></el-option>
                          <el-option label="9" value="9"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="启用/禁用" label-width="134px" prop="isUse">
              <el-radio-group v-model="ruleForm.isUse">
                <el-radio label="1">启用</el-radio>
                <el-radio label="2">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item class="news-template-btn">
              <el-button type="primary" size="small" @click="submitForm('ruleForm')">下一步：设置模板规则参数</el-button>
              <el-button size="small" @click="backPage">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
  </div>
  <el-dialog :visible="dialogVisible"
             :show-close="true"
             :before-close="close"
             width="50%"
             title="文件预览"
  >
    <pdf :src="FeileSrc" v-for="i in numPages" :page="i" :key="i"></pdf>
  </el-dialog>
  </div>
</template>

<script>
import { getscopedataapi, viewdocx, getbase } from '@/api/contractTemplate.js'
import pdf from 'vue-pdf'
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js'
export default {
  data () {
    return {
      dialogVisible: false,
      basestr: '',
      FeileSrc: '',
      numPages: 0,
      title: '编辑模板',
      isChecked: true,
      showName: false,
      showNumber: false,
      getstr: '',
      isclick: true,
      n: 10,
      scopelist: [],
      ruleForm: {
        name: '',
        number: '',
        type: '2',
        range: null,
        iconList: [],
        draftList: [],
        message: '',
        isUse: '1',
        datetype: '固定日期',
        date1: '',
        date2: '',
        startdate: '当天',
        newdate: '',
        lv: '1',
        file: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入模板编号', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择合同类型', trigger: 'change' }
        ],
        range: [
          { required: true, message: '请选择适用范围', trigger: 'change' }
        ],
        iconList: [
          { required: true, message: '请选上传模板图标', trigger: 'change' }
        ],
        draftList: [
          { required: true, message: '请选上传模板底稿', trigger: 'change' }
        ],
        datetype: [
          { required: true, message: '请选择模板有效期', trigger: 'change' }
        ],
        date1: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        date2: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        startdate: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        newdate: [
          { required: false, message: '请输入天数', trigger: 'blur' }
        ]
      },
      fileName: '',
      updateFile: '',
      isupload: ''
    }
  },
  components: {
    pdf
  },
  watch: {
    'ruleForm.draftList' (val, newval) {
      if (val[0].name !== newval[0].name) {
        const span = document.getElementsByClassName('viewdecx')[0]
        span.remove()
      }
    }
  },
  methods: {
    getbase () {
      getbase({
        transId: '06234024',
        accessHost: '11',
        cifSeq: '1',
        id: this.$route.query.id
      }).then(res => {
        if (res.data.code === '000000') {
          this.getstr === '' ? this.basestr = res.data.data.baseStr : this.basestr = this.getstr
        }
      })
    },
    getscopedata () {
      getscopedataapi({
        transId: '06234019',
        accessHost: '20101',
        cifSeq: '300000454'
      }).then(res => {
        if (res.data.code === '000000') {
          this.scopelist = res.data.data.list
        }
      })
    },
    close () {
      this.dialogVisible = false
    },
    submitForm (formName) {
      // 缓存页面数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let stTime = this.ruleForm.date1
          let endTime = this.ruleForm.date2
          if (typeof (this.ruleForm.date1) !== 'string') {
            let month = (this.ruleForm.date1.getMonth() + 1)
            if (month < 10) {
              month = '0' + month
            }
            let newDate = this.ruleForm.date1.getDate()
            if (newDate < 10) {
              newDate = '0' + newDate
            }
            stTime = this.ruleForm.date1.getFullYear() + '-' + month + '-' + newDate
          }
          if (typeof (this.ruleForm.date2) !== 'string') {
            let month2 = (this.ruleForm.date2.getMonth() + 1)
            if (month2 < 10) {
              month2 = '0' + month2
            }
            let newDate2 = this.ruleForm.date2.getDate()
            if (newDate2 < 10) {
              newDate2 = '0' + newDate2
            }
            endTime = this.ruleForm.date2.getFullYear() + '-' + month2 + '-' + newDate2
          }
          const data = {
            templateName: this.ruleForm.name.trim(),
            typeId: parseInt(this.ruleForm.type),
            scopeId: parseInt(this.ruleForm.range),
            fileName: this.fileName,
            baseStr: this.getstr === '' ? this.basestr : this.getstr,
            startDate: stTime,
            endDate: endTime,
            details: this.ruleForm.message.trim(),
            contractLevel: parseInt(this.ruleForm.lv),
            enable: parseInt(this.ruleForm.isUse),
            templateNo: this.ruleForm.number,
            isupload: this.isupload
          }
          window.localStorage.setItem('setData', JSON.stringify(data))
          this.$router.push({
            name: 'templateParam',
            query: {
              isgin: 'isedit'
            }
          })
        } else {
          return false
        }
      })
    },
    ShowFile (base) {
      const datas = 'data:application/pdf;base64,' + base
      this.FeileSrc = pdf.createLoadingTask({ url: datas, CMapReaderFactory })
      this.FeileSrc.promise.then((pdf) => {
        this.numPages = pdf.numPages
      })
    },
    editName () {
      this.showName = !this.showName
    },
    backPage () {
      // 取消操作 清除缓存
      window.localStorage.removeItem('setData')
      window.localStorage.removeItem('templateDate')
      this.$router.push({
        name:'templateList'
      })
    },
    radioChecked (val) {
      if (val === '固定日期') {
        this.rules.date1[0].required = true
        this.rules.date2[0].required = true
        this.rules.startdate[0].required = false
        this.rules.newdate[0].required = false
      } else if (val === '启用后') {
        this.rules.date1[0].required = false
        this.rules.date2[0].required = false
        this.rules.startdate[0].required = true
        this.rules.newdate[0].required = true
      }
    },
    handleRemoveIcon (file, fileList) {
      this.ruleForm.iconList = fileList
    },
    handleChangeIcon (file, fileList) {
      this.ruleForm.iconList = fileList
    },
    handleRemoveDraft (file, fileList) {
      // 删除上传文件
      this.ruleForm.draftList = fileList
      this.fileName = ''
      this.updateFile = ''
      const span = document.getElementsByClassName('viewdecx')[0]
      span.remove()
    },
    handleChangeDraft (file, fileList) {
      this.$refs.upload.clearFiles()
      // 上传文件列表发生变化
      const type1 = file.name.substring(file.name.lastIndexOf('.') + 1)
      this.ruleForm.draftList = fileList
      if (type1 !== 'docx') {
        this.$message({
          message: '上传文件只能是 doc、docx格式!',
          type: 'error'
        })
        this.ruleForm.draftList = []
      } else {
        if (fileList.length > 1) {
          fileList.shift()
        }
        this.isupload = 'up'
        const newFile = file.raw
        this.getBase64File(newFile).then(res => {
          const params = res.split(';base64,')
          this.basestr = params[1]
          this.getstr = this.basestr
          this.updateFile = params[1]
        })
        const span = document.createElement('span')
        span.className = 'viewdecx'
        span.innerHTML = '<i class="el-icon-view"></i>预览docx'
        span.style.color = '#409EFF'
        span.style.cursor = 'pointer'
        span.style.marginLeft = '10px'
        span.onclick = this.viewdoc
        document.getElementById('uploaddom').appendChild(span)
      }
      this.fileName = file.name.split('.')[0]
    },
    viewdoc () {
      if (this.isclick) {
        this.isclick = false
        const viewBtn = document.getElementsByClassName('viewdecx')[0]
        const b = document.createElement('b')
        b.style.color = '#999'
        b.style.margin = '0px 15px'
        b.style.fontWeight = 'normal'
        viewBtn.style.color = '#ccc'
        viewBtn.style.cursor = 'default'
        const timer = setInterval(() => {
          const index = this.n--
          b.innerHTML = `(${index}s)`
          if (index <= 0) {
            this.n = 10
            b.remove()
            viewBtn.style.color = '#409EFF'
            viewBtn.style.cursor = 'pointer'
            clearInterval(timer)
            this.isclick = true
          }
        }, 1000)
        document.getElementById('uploaddom').appendChild(b)
        viewdocx({
          transId: '06135009',
          accessHost: '1111',
          baseStr: this.basestr
        }).then(res => {
          if (res.data.code === '000000') {
            this.dialogVisible = true
            this.ShowFile(res.data.data.baseStr)
          }
        })
      } else {
        this.$message({
          type: 'error',
          message: `请${this.n}秒后重新点击预览`
        })
      }
    },
    getBase64File (file) {
      // basse64文件转换
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        let updateFile = ''
        reader.onload = () => {
          updateFile = reader.result
        }
        reader.onerror = error => {
          reject(error)
        }
        reader.onloadend = () => {
          resolve(updateFile)
        }
      })
    },
    handleTimeChange () {
      // 时间校验
      if (this.ruleForm.date1 !== '' && this.ruleForm.date2 !== '') {
        const date1 = new Date(this.ruleForm.date1).getTime()
        const date2 = new Date(this.ruleForm.date2).getTime()
        if (date1 > date2) {
          this.$message({
            message: '到期时间不得早于起始时间',
            type: 'error'
          })
          this.ruleForm.date2 = ''
        }
      }
    }
  },
  mounted () {
    // 获取编辑的模板数据
    const templateData = JSON.parse(window.localStorage.getItem('templateDate'))
    const setData = JSON.parse(window.localStorage.getItem('setData'))
    setData ? this.getstr = setData.baseStr : this.getstr = ''
    this.ruleForm.name = templateData.templateName
    this.ruleForm.number = templateData.templateNo
    this.ruleForm.type = String(templateData.typeId)
    this.ruleForm.range = templateData.scopeId
    if (templateData.path !== '') {
      const fileData = {
        name: templateData.path.split('/')[templateData.path.split('/').length - 1],
        url: ''
      }
      this.ruleForm.draftList.push(fileData)
      if (this.ruleForm.draftList.length !== 0) {
        const span = document.createElement('span')
        span.className = 'viewdecx'
        span.innerHTML = '<i class="el-icon-view"></i>预览docx'
        span.style.color = '#409EFF'
        span.style.cursor = 'pointer'
        span.style.marginLeft = '10px'
        span.onclick = this.viewdoc
        document.getElementById('uploaddom').appendChild(span)
      }
    }
    this.updateFile = ''
    this.fileName = (templateData.path.split('/')[templateData.path.split('/').length - 1]).split('.')[0]
    this.ruleForm.date1 = templateData.startDate
    this.ruleForm.date2 = templateData.endDate
    if (templateData.details === null) {
      this.ruleForm.message = ''
    } else {
      this.ruleForm.message = templateData.details
    }
    this.ruleForm.lv = String(templateData.contractLevel)
    this.ruleForm.isUse = String(templateData.enable)
    this.getscopedata()
    this.getbase()
  }
}
</script>

<style scoped>
.news-template{
    width: 100%;
    min-height: 100%;
    background: #fff;
}
.news-template-title {
  height: 64px;
  margin-bottom: 20px;
}
.news-template-title i{
  width: 4px;
  height: 16px;
  background: #5290FF;
  display: inline-block;
  margin-right: 10px;
  vertical-align: middle;
}
.news-template-title h3{
  margin: 0 26px;
  padding-left: 3px;
  font-size: 14px;
  line-height: 64px;
  font-weight: bold;
  border-bottom: 1px solid rgba(187, 187, 187, 0.43);
}
.news-template-box {
  margin: 0 26px;
  padding: 40px 0 80px 0;
}
.news-template-box >>> .el-form-item__label {
    text-align: left;
    line-height: 36px;
}
.news-template-box >>> .el-form-item {
    margin-bottom: 15px;
    height: 36px;
}
.news-template-box >>> .el-input__inner{
  height: 30px;
  font-size: 14px;
  width: 496px;
}
.news-template-box >>> .el-form-item__content{
  line-height: 36px;
}
.news-template-box >>> .el-form-item__error{
  padding-top: 2px;
}
.upload-demo{
  display: flex;
  height: 36px;
  line-height: 36px;
  align-items: center;
}
.upload-demo i{
  margin-right: 6px;
}
.upload-demo >>> .el-upload__tip{
  margin-top: 0;
  margin-left: 10px;
  margin-right: 20px;
}
.upload-demo >>> .el-upload-list{
  display: flex;
  align-items: center;
}
.upload-demo >>> .el-upload-list__item{
  margin: 0;
}
.news-template-box .form-indate{
  height: auto;
}
.form-indate >>> .el-form-item__content{
  margin: 0;
}
.form-indate >>> .el-radio-group {
  display: flex;
  flex-direction: column;
}
.form-indate >>> .form-indate-item {
  height: 36px;
  width: 180px;
}
.form-indate >>> .form-indate-item .el-date-editor{
  width: 180px;
}
.form-indate >>> .form-indate-item .el-input__inner{
  width: 180px;
}
.form-indate >>> .line{
 font-size: 14px;
 width: 40px;
 text-align: center;
}
.form-indate >>> .el-radio {
  width: 95px;
  margin: 0;
}
.form-indate >>> .line-2{
  width: 113px;
  margin: 0 6px;
}
.form-indate >>> .new-date{
  position: relative;
  width: 94px;
}
.form-indate >>> .new-date .el-input__inner{
  width: 94px;
  padding-right: 24px;
}
.form-indate >>> .new-date .unit-icon{
  position: absolute;
  right: 6px;
  font-style: normal;
}
.form-indate >>> .el-row{
  margin-bottom: 15px;
}
.news-template-btn >>> .el-form-item__content {
  margin: 30px 0 0 185px !important;
}
.news-template-btn >>> .el-button--primary{
  margin-right: 24px;
}
.icon-list >>> .el-form-item__content{
    display: flex;
}
.icon-list >>> .icon-list-item{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 10px;
}
.icon-list >>> .icon-list-item i{
    font-size: 24px;
    margin: 0 6px;
    color: #409EFF;
}
.icon-list >>> .file-list-item{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 10px;
}
.icon-list >>> .file-list-item i{
    font-size: 14px;
    margin: 0 6px;
    color: #409EFF;
    font-style: normal;
}
.news-template-box .lv-input >>> .el-input__inner {
  width: 100px;
}
</style>
